const TABKEY = 9;

var submissions;
var tags;

function refreshTable(){
	$("#submissionlist").children().fadeOut(function(){ 
		$(this).remove(); 
		$("#submissionlist").hide();
		var i = 1;
		for(index in submissions){
			$("#submissionlist").append($('<tr class="submission' + ((i % 2 == 0)? '' : ' alt') + '" id="sub' + i + '" name="sub' + submissions[index].id + '"><td class="decision">' + submissions[index].decision + '</td><td class="result">' + submissions[index].result + '</td><td><input class="submissionID" type="hidden" value="' + submissions[index].id + '" /><a style="cursor:pointer" class="qqButton"><img src="/bottleIcon.png" /></a></td><td><a style="cursor:pointer" class="trashButton"><img src="/trash.png" /></a></td></tr>'));
			i++;
		}
		$("#submissionlist").show();
		bindButtons();
	});
}

function updateTotals(){
	API.call({
		action: 'getLengths',
		args: {},
		onComplete: function(data){
			$("#queueCount").flipCounter('updateValueTo', data.queue);
			$("#submissionsCount").flipCounter('updateValueTo', data.submissions);
		}
	});
}

function matchingTags(input){
	var result = [];
	$.each(tags, function(index, value){
		if(value.name.toLowerCase().indexOf(input.toLowerCase()) != -1){
			//console.log('matched: ' + value.name);
			result = addToArray(value, result);
		}
	});
	
	return result;
}

function addToArray(ele, arr){
	if(arr.length < 1){
		//console.log('empty array, splicing on 0');
		arr.splice(0, 0, ele);
	}else{
		//console.log('array exists, finding splice point');
		var flagDone = false;
		$.each(arr, function(index, value){
			if(value.usage <= ele.usage){
				//console.log('splicing on ' + index);
				flagDone = true;
				arr.splice(index, 0, ele);
				return false;
			}
		});
		if(!flagDone){
			//console.log('no splice point, pushing');
			arr.push(ele);
		}
	}
	return arr;
}

function bindTagLinks(){
	$(".tagSuggestion").click(function(){
		console.log('wat');
		var strIndex = $("#qqTags").val().lastIndexOf(',');
		strIndex = (strIndex == -1) ? 0 : strIndex + 1;
		$("#qqTags").val($("#qqTags").val().substring(0, strIndex) + $(this).html() + ', ');
		$("#qqTags").focus();
	});
}

function tabComplete(value){
	
	var matches = matchingTags(value);
	$.each(matches, function(index, value){
		$("#tagMatches").append('<span class="tagSuggestion">' + value.name + '</span>, ');
	});
	bindTagLinks();
}

function refreshData(redraw){
	if(redraw){
		$("#submissionlist").children().fadeOut(function(){ 
			$(this).remove();
			$("#submissionlist").append($('<tr><td colspan="4"><img src="/images/spinner.gif" /> Loading...</td></tr>'));
			API.call({
				action: 'getSubmissions',
				args: {},
				onComplete: function(data){
					submissions = data;
					refreshTable();
					API.call({
						action: 'getTags',
						args: {},
						onComplete: function(data){
							tags = data;
							updateTotals();
						}
					});
				}
			});
		});
	}else{
		API.call({
			action: 'getSubmissions',
			args: {},
			onComplete: function(data){
				submissions = data;
				API.call({
					action: 'getTags',
					args: {},
					onComplete: function(data){
						tags = data;
					}
				});
			}
		});
	}
}

function bindButtons(){
	$("a.qqButton").click(function(e){
		e.preventDefault();
		fillFormFields($(this).siblings("input.submissionID").val());
		
		$("#showqq").trigger("click");
	});
	
	$("a.trashButton").click(function(e){
		e.preventDefault();
		
		var doit = confirm('Do you really wanna?');
		if(doit){
			$(this).parent().parent().attr("id", "deleteMe");
			API.call({
				action: 'deleteSubmissionByID',
				args: {
					id: $("tr#deleteMe").children("td").children("input.submissionID").val()
				},
				onComplete: function(data){
				$("tr#deleteMe").fadeOut("slow", function(){
					$(this).remove();
					updateTotals();
				});	
				},
				onFailure: function(data){
					alert('Couldnt delete it: ' + data.reason);
				}
			});
		}
	});
}

function disableForm(){
	$("#qqer").children("p").children(":input").attr("disabled", "polio");
}

function enableForm(){
	$("#qqer").children("p").children(":input").removeAttr("disabled");
}

function fillFormFields(id){
	enableForm()
	var decision = $("tr[name=sub" + id + "]").children("td.decision").html();
	var result = $("tr[name=sub" + id + "]").children("td.result").html();
	$("#qqDecision").val(decision);
	$("#qqResult").val(result);
	$("#qqTags").val('');
	$("#qqID").val(id + '');
	//console.log(id);
}

function updateStatus(spinner, message){
	$("#qqStatus").html('<img src="/images/spinner.gif" /> ' + message);
}

$(document).ready(function(){

	$("#queueCount").flipCounter({digits: 4});
	$("#submissionsCount").flipCounter({digits: 4});
	
	refreshData(true);
	
	$("form#qqer").submit(function(e){
		e.preventDefault();
		
		disableForm();
		updateStatus(true, 'Sending...');
		
		API.call({
			action: 'enqueueSubmission',
			args: {
				id: $("#qqID").val(),
				decision: $("#qqDecision").val(),
				result: $("#qqResult").val(),
				tags: $("#qqTags").val()
			},
			onComplete: function(data){
				updateStatus(false, 'BETTER THAN CHRISTMAS! Refreshing...');
				setTimeout('$.modal.close();', 3000);
				$("tr[name=sub" + $("#qqID").val() + "]").fadeOut(function(){
					$(this).remove();
				});
				refreshData(false);
			},
			onFailure: function(data){
				updateStatus(false, 'BORKND: ' + data.reason);
				enableForm();
			}
		});
	});
	
	$("#qqTags").keydown(function(eo){
		if($("#tagMatches").is(":visible")){
			$("#tagMatches").slideUp('fast');
		}
		if(eo.keyCode == TABKEY){
			eo.preventDefault();
			var strIndex = $("#qqTags").val().lastIndexOf(',');
			strIndex = (strIndex == -1) ? 0 : strIndex + 1;			
			console.log('checking ' + $("#qqTags").val().substr(strIndex));
			$("#tagMatches").html('');
			$("#tagMatches").slideDown('fast');
			tabComplete($("#qqTags").val().substr(strIndex));
		}
	});
	
	$("#qqTags").blur(function(eo){
		$("#tagMatches").slideUp('fast');
	});
	
	
});